const jwt = require('jwt-simple')
const KEY = "&^$"
// 生成随机数
module.exports.getRandom = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
module.exports.json = function (res, ok = -1, msg = "网络连接错误") {
    res.json({
        ok,
        msg
    })
}
module.exports.changArr = function (arr, len = 10) {
    const arr2 = []
    for (var i = 0; i < arr.length; i += len) {
        arr2.push(arr.slice(i, i + len))
    }
    return arr2
}
// 生成token
module.exports.encode = function (adminName, lastTime = Date.now() + 1000 * 60 * 60) {
    return jwt.encode({
        adminName,
        lastTime
    }, KEY)
}
// 解析token
module.exports.decode = function (token) {
    try {
        const info = jwt.decode(token, KEY)
        if (info.lastTime > Date.now()) {
            // 未过期
            return {
                ok: 1,
                info,
                msg: '成功'
            }
        } else {
            return {
                ok: -1,
                msg: "token过期了"
            }
        }
    } catch (err) {
        return {
            ok: -1,
            msg: "网络连接错误"
        }
    }
}